﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Drawing;
using MbWsClient.Service.Enums;
using MbWsClient.ServiceClasses;

namespace MbWsClient.Classes
{
    public class ImageDictionary
    {
        Guid _id;
        Dictionary<ImageTypes, string> _images = new Dictionary<ImageTypes, string>();

        public ImageDictionary(Guid id)
        {
            _id = id;
        }

        public string GetImage(ImageTypes type)
        {
            if (_images.ContainsKey(type))
            {
                return _images[type];
            }
            else
            {
                string fileName = _id.ToString() + "." + type.ToString();
                AppSettings.ImageCacheDir.EnsureDirectoryExistance();
                FileInfo[] files = AppSettings.ImageCacheDir.GetFiles(fileName + "*");
                if (files.Length == 1)
                {
                    return GetImage(files[0]);
                }
                else
                {
                    string path = Path.Combine(AppSettings.ImageCacheDir.FullName, fileName + ".jpg");
                    try
                    {
                        PictureItem pictureItem = AppSettings.MbService.GetImage(_id, type, 500, 500);
                        if (pictureItem.PictureStream != null)
                        {
                            MemoryStream ms = new MemoryStream(pictureItem.PictureStream);
                            Image returnImage = Image.FromStream(ms);
                            returnImage.Save(path);
                            _images.Add(type, path);
                        }
                        else
                        {
                            path = ConfigHelper.GetConfigValue(MbWsClient.Enum.ConfigSetting.UnkownImage);
                        }
                    }
                    catch (Exception)
                    {
                        path = ConfigHelper.GetConfigValue(MbWsClient.Enum.ConfigSetting.UnkownImage);
                    }
                    return path;
                }
            }
        }

        private string GetImage(FileInfo file)
        {
            return file.FullName;
        }
    }
}
